<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>new service</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="public/layui/css/layui.css" media="all">

    <style>
        .layui-form-item .layui-form-checkbox[lay-skin=primary] {
            margin-top: 0px;
        }

        .layui-tab {
            margin: 0;
        }
    </style>
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body style="padding-left: 6px;overflow: hidden">
<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="abilityTpl">
    <a href="javascript:;" data-id="{{ d.abilityId }}" class="layui-table-link" name="ability-btn"
       target="_blank">{{ d.abilityName }}</a>
</script>
<script type="text/html" id="stateTpl">
    <!-- 这里的 checked 的状态只是演示 -->
    <input type="checkbox" name="stateIn" data-id="{{ d.id }}" value="{{d.state}}" lay-skin="switch" lay-text="运行|停止"
           lay-filter="stateIn" {{ d.state== 'on' ? 'checked' : '' }}>
</script>
<div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">

    <ul class="layui-tab-title">
        <li class="layui-this">新增</li>
        <li>实例列表</li>

    </ul>
    <div class="layui-tab-content">

        <div class="layui-tab-item layui-show layui-form">
            <div class="layui-form layui-form-pane" id="ability-form">
                <div class="layui-form-item">
                    <label class="layui-form-label">选择能力</label>
                    <div class="layui-input-inline">
                        <select name="abilityId" id="abilityId" lay-verify="required" lay-search="">
                            <option value="">请选择</option>
                        </select>

                    </div>

                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">超时时间</label>
                    <div class="layui-input-inline">
                        <input type="text" name="timeout" lay-verify="required|number" value="9000" autocomplete="off"
                               class="layui-input">
                    </div>
                    <div class="layui-form-mid layui-word-aux">超时时间(ms毫秒)(-1 不限制;0 继承)</div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">限流设置</label>
                    <div class="layui-input-inline">
                        <input type="text" name="rateLimit" lay-verify="required|number" value="-1" placeholder="-1 不限流"
                               autocomplete="off" class="layui-input">
                    </div>
                    <div class="layui-form-mid layui-word-aux">每分钟最大流量(-1 不限流;0 继承)</div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">超时次数</label>
                    <div class="layui-input-inline">
                        <input type="text" name="maxTimeoutTimes" lay-verify="number" value="-1" placeholder="-1 不限制"
                               autocomplete="off" class="layui-input">
                    </div>
                    <div class="layui-form-mid layui-word-aux">使用能力超时次数（分钟）(-1不限制;0 继承)</div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">是否启用</label>
                    <div class="layui-input-block">
                        <input type="checkbox" name="state" id="state" lay-filter="state" lay-verify="state"
                               lay-skin="switch"
                               lay-text="启用|关闭">
                    </div>
                </div>
                <div class="layui-form-item" style="margin-bottom:0">
                    <div class="layui-input-block" style="text-align:right;">
                        <button class="layui-btn layui-btn-sm" id="add-instance" lay-submit=""
                                lay-filter="add-instance">立即提交
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="layui-tab-item">
            <div class="layui-form layui-form-pane" id="ability-form">
                <div class="layui-form-item layui-form-text">
                    <div class="layui-input-block">
                        <table class="layui-table" lay-data="{even:true, page:false, id:'uaList'}"
                               lay-filter="uaList">
                            <thead>
                            <tr>
                                <th lay-data="{type:'numbers'}"></th>
                                <th lay-data="{field:'abilityName', minWdith:120, templet:'#abilityTpl'}">能力</th>
                                <th lay-data="{field:'rateLimit', width:64, edit: 'text'}">限流</th>
                                <th lay-data="{field:'timeout', width:64, edit: 'text'}">超时</th>
                                <th lay-data="{field:'maxTimeoutTimes',width:64, edit: 'text'}">次数</th>
                                <th lay-data="{field:'stateIn',width:80, templet: '#stateTpl'}">状态</th>
                                <th lay-data="{field:'op',width:80, toolbar:'#tableBar'}">操作</th>
                                <!-- 运行 挂起  关闭-->
                            </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>


<script src="public/layui/layui.js" charset="utf-8"></script>
<script src="js/jquery-3.2.1.js"></script>
<script src="js/loader.js"></script>
<script>
    layui.use(['form', 'laydate', 'oka', 'table'], function () {
        var form = layui.form
            , layer = layui.layer
            , laydate = layui.laydate
            , table = layui.table
            , oka = layui.oka;
        //alert(location.hash);
        //自定义验证规则

        var clientId = location.hash;
        if (clientId == "") {
            layer.msg('参数错误!!！', {
                offset: "t",
                anim: 6
            });
            return false;
        }
        clientId = clientId.substring(1);
        $.ajax({
            url: "/admin/ability"
            , type: "GET"
            , dataType: "json"
            , async: true
            , success: function (res) {
                oka.loading.close();
                //obj = null;
                var dom = $("#abilityId");
                for (var i = 0, len = res.data.length; i < len; i++) {
                    var option = document.createElement("option");
                    var item = "<option value='" + res.data[i]["id"] + "'>" + res.data[i]["name"] + "</option>";
                    dom.append(item);
                }
                form.render("select");
                dom = null;

            }
        });
        $.ajax({
            url: "/admin/uas/" + clientId
            , type: "GET"
            , dataType: "json"
            , async: true
            , success: function (res) {
                oka.loading.close();


                table.reload("uaList", res)
            }
        });
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            }
            , content: function (value) {
                alert(value)
            }
        });
        form.on('switch(stateIn)', function (data) {


            var formData = {id: this.getAttribute("data-id")};
            formData["state"] = this.checked ? 'on' : 'off';
            $.ajax({
                url: "/admin/ua/" + formData.id
                , type: "PUT"
                , dataType: "json"
                , contentType: "application/json"
                , async: true
                , data: JSON.stringify(formData)
                , success: function (res) {
                    oka.loading.close();
                    if (res.code == "0") {

                        layer.msg('操作失败!!！', {
                            offset: "t",
                            anim: 6
                        });

                    } else {
                        layer.msg('操作成功',{
                            time: 600
                        },function(){
                            alert()
                        });


                    }
                }
            });

        });

        form.on('switch(state)', function (data) {
            $("#state").prop("value", this.checked ? 'on' : 'off');


        });
        //监听提交

        table.on('tool(uaList)', function (obj) {
            var data = obj.data;
            console.log(obj.event + "===" + data);
            if (obj.event === 'del') {
                layer.confirm('确认要取消关联这个能力？', function (index) {
                    oka.loading.open();
                    $.ajax({
                        url: "/admin/ua/" + data.id
                        , type: "DELETE"
                        , dataType: "json"
                        , async: true
                        , success: function (res) {
                            oka.loading.close();
                            if (res.bizCode == "1") {
                                obj.del();
                                layer.close(index);
                                layer.msg('操作成功');
                            } else {
                                layer.msg('操作失败!!！', {
                                    offset: "t",
                                    anim: 6
                                });
                            }
                            obj = null;

                        }
                    });
                });
            }
        });

        table.on('edit(uaList)', function (obj) {
            console.log(obj)
            var value = obj.value
                , data = obj.data
                , field = obj.field;
            if (!isNaN(value)) {
                var formData = {id: data.id};
                formData[field] = value;
                $.ajax({
                    url: "/admin/ua/" + formData.id
                    , type: "PUT"
                    , dataType: "json"
                    , contentType: "application/json"
                    , async: true
                    , data: JSON.stringify(formData)
                    , success: function (res) {
                        oka.loading.close();
                        if (res.code == "0") {

                            layer.msg('操作失败!!！', {
                                offset: "t",
                                anim: 6
                            });

                        } else {
                            layer.msg('操作成功');


                        }
                    }
                });
            } else {
                layer.msg('数字类型', {icon: 2});
                return false;
            }
            //layer.msg('请重新输入', {icon: 2});
            //layer.msg('[ID: '+ data.id +'] ' + field + ' 字段更改为：'+ value);
            return false;
        });
        form.on('submit(add-instance)', function (data) {
            //oka.loading.open();

            var formData = data.field;
            formData.clientId = clientId;
            formData.abilityName = $("[name='abilityId']").find("option:selected").text()
            if (data.field.state == undefined) {
                data.field.state = "off";
            }
            $.ajax({
                url: "/admin/ua"
                , type: "POST"
                , dataType: "json"
                , contentType: "application/json"
                , async: true
                , data: JSON.stringify(formData)
                , success: function (res) {
                    oka.loading.close();
                    if (res.code == "0") {

                        layer.msg('操作失败!!！', {
                            offset: "t",
                            anim: 6
                        });

                    } else {
                        layer.msg('操作成功');
                        var d = table.cache.uaList.slice();
                        if (res.bizDesc != "") {

                            formData.id = res.bizDesc;
                        }
                        console.log(formData);
                        //data.field.machineInfo = ($("[name='machineId']").find("option:selected").text());

                        d.push(formData);
                        table.reload("uaList", {
                            data: d
                        })

                    }
                }
            });


            return false;
        });


        $(document).on('click', '.layui-table>tbody>tr', function (e) {
            //console.log($(this)[0])

            if (e.target.name == "ability-btn") {
                var name = e.target.getAttribute("data-id");
                parent.layer.open({
                    type: 2,
                    title: "查看实例",
                    content: ["addAbility.html#!" + name, 'yes'],
                    area: ['700px', '480px'],
                    end: function () {
                        if (oka.page.ret != undefined) {
                            var ret = JSON.parse(oka.page.ret);
                            delete oka.page["ret"];
                            obj.update(ret);
                            console.log(ret);
                            if (ret.status == "on") {
                                obj.tr[0].querySelector('[name="status"]').setAttribute("checked", true);
                            } else {
                                obj.tr[0].querySelector('[name="status"]').removeAttribute("checked");
                            }


                            form.render();
                        }

                    }
                });
            }

        })
    });
</script>

</body>
</html>